package org.example.aidemo.controller;

import org.example.aidemo.pojo.EmailMessage;
import org.example.aidemo.pojo.Location;
import org.example.aidemo.pojo.Result;
import org.example.aidemo.pojo.UserCredentials;
import org.example.aidemo.service.UserCredentialsService;
import org.example.aidemo.service.UserService;
import org.example.aidemo.service.common.AutoNaviService;
import org.example.aidemo.service.common.QQEmailService;
import org.example.aidemo.utils.SecurityUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.sql.Time;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/userCredentials")
public class UserCredentialsController {
    @Autowired
    private UserCredentialsService userCredentialsService;
    @Autowired
    private QQEmailService qqEmailService;
    @Autowired
    private UserService userService;
    @Autowired
    private SecurityUtils securityUtils;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate<String, Location> redisLocation;
    @Autowired
    private AutoNaviService autoNaviService;
    // 使用 ConcurrentHashMap 作为简单的内存缓存
    private final Map<Long, Boolean> userAccessedMap = new ConcurrentHashMap<>();
    @PostMapping("/addUserCredentials")
    public Result<UserCredentials> addUserCredentials(@RequestBody UserCredentials userCredentials) {
        UserCredentials userCredentials2  =userCredentialsService.
                addUserCredentials(userCredentials.getPlatformName(),userCredentials.getPlatformUrl(),
                        userCredentials.getAccountUsername(),userCredentials.getEncryptedPassword());
        return Result.success(userCredentials2);
    }
    @GetMapping("/getUserCredentialsByUserId")
    public Result<List<UserCredentials>> getUserCredentialsByUserId(@RequestParam Long userId) {
        List<UserCredentials> userCredentials=userCredentialsService.getUserCredentialsByUserId(userId);
        /**
         * 访问敏感接口，触发任务
         */
        if (!userAccessedMap.containsKey(userId)) {
            Location location = redisLocation.opsForValue().get("user:location:" + userId);
            String email = userService.findByUsername(securityUtils.getCurrentUsername()).getEmail();
            Time currentTime = new Time(System.currentTimeMillis());
            String address = autoNaviService.
                    getAddressByCoordinates(location.getLongitude().toString(), location.getLatitude().toString());
            EmailMessage emailMessage = new EmailMessage(
                    email,
                    "您的备忘录密码页访问提醒",
                    "您在" + currentTime + "访问了Ai备忘录系统，请及时处理。若不是本人访问，请确保您账号的安全风险"+
                            "。访问地点:"+address
            );
            rabbitTemplate.convertAndSend("email.exchange", "email.routing.key", emailMessage);
            userAccessedMap.put(userId, true);
        }
        return Result.success(userCredentials);
    }
    @DeleteMapping("/deleteUserCredentials/{ids}")
    Result<String> deleteUserCredentials(@PathVariable("ids") List<Long> ids) {
        Result<String> result = new Result<>();
        userCredentialsService.deleteUserCredentials(ids);
        result.setCode("200");
        result.setMsg("删除成功！");
        return result;
    }
}
